const http = require('http')

const errMessage = (req, res, next) => {
    res.cc = (err, stat = -1) => {
        return res.send({
            code: stat,
            msg: err instanceof Error ? err.message : err
        })
    }
    next()
}

// 格式化日期和时间（UTC+8）
const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
    timeZone: 'Asia/Shanghai' // 亚洲/上海时区（UTC+8）
}

// 请求日志
const reqLog = (req, res, next) => {
    const now = new Date()
    console.log('--------------------------------------------------------------------------------')
    console.log(now.toLocaleString('zh-CN', options), 'req')
    console.log('method:', req.method, '  url:', req.originalUrl, '  httpVersion:', req.httpVersion)
    console.log('headers:', req.headers)
    console.log('user:', req.user)
    console.log('body:', req.body)
    console.log('--------------------------------------------------------------------------------')
    next()
}

// 响应日志
const resLog = (req, res, next) => {
    const originalSend = res.send
    res.send = function (body) {
        const now = new Date()
        console.log('--------------------------------------------------------------------------------')
        console.log(now.toLocaleString('zh-CN', options), 'res')
        console.log('httpVersion:', req.httpVersion, '  statusCode:', this.statusCode, '  statusMSG:', this.statusMessage || http.STATUS_CODES[this.statusCode])
        console.log('headers:', this.getHeaders())

        try {
            // 尝试解析 JSON 响应体
            console.log('body:', JSON.parse(body))
        } catch (e) {
            // 非 JSON 响应直接输出
            console.log('body:', body)
        }
        console.log('--------------------------------------------------------------------------------')
        return originalSend.call(this, body)
    }

    next()
}

// token失效请求日志
const tokenLog = (req, res) => {
    const now = new Date()
    console.log('--------------------------------------------------------------------------------')
    console.log(now.toLocaleString('zh-CN', options), 'req')
    console.log('method:', req.method, '  url:', req.originalUrl, '  httpVersion:', req.httpVersion)
    console.log('headers:', req.headers)
    console.log('user:', 'token expiration')
    console.log('body:', req.body)
    console.log('--------------------------------------------------------------------------------')
}

module.exports = {
    errMessage,
    reqLog,
    resLog,
    tokenLog
}